from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import random
import redis

# def dragon(request):
#     if request.method == "GET":
#         return render(request,'index.html')


class FishAPIView(APIView):
    def get(self,request):
        # 1.获取用户手机号
        phone = request.query_params.get("phone")
        key = "sms_code:%s"%phone
        flag = "sms_flag:%s"%phone

        # 2.生成短信验证码
        r = redis.Redis(host='localhost', port=6379, db=0, password='123')
        stored_flag = r.get(flag)
        if stored_flag:
            r.close()
            return Response({"code":204, "err":"已生成短息验证码！"})
        v_code = random.randint(1000,9999)

        # 3.存储验证码 到redis中
        r.set(key, v_code, ex=300)
        r.set(flag, 1, ex=60)
        return Response({"code":200, "msg":"生成验证码成功！", "smsCode":v_code})

    def post(self,request):
        # 1.获取前端数据
        sms_code = request.data.get("smsCode")
        phone = request.data.get("phone")

        # 2.手机号构造key
        key = "sms_code:%s"%phone

        # 3.连接redis
        r = redis.Redis(host="localhost", port=6379, db=0, password='123')
        stored_code = r.get(key)
        if not stored_code:
            r.close()
            return Response({"code":204, "err":"验证码已过期！"})
        else:
            if stored_code.decode() == sms_code:
                r.close()
                return Response({"code":200, "msg":"验证成功！"})
            else:
                r.close()
                return Response({"code":204, "err":"验证失败！"})